/**
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/4/14 01:44
 */
package org.mechanic.fund.domain.system.manager;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.mechanic.fund.domain.BaseEntity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.HashSet;
import java.util.Set;

/**
 * 系统角色实体
 *
 * @author mechanic
 * @version 0.0.1
 */
@Entity
@Table(name = "sys_role")
public class Role extends BaseEntity {

    private static final long serialVersionUID = 2572724088948554477L;
    /**
     * 名称
     */
    @Column(name = "name")
    private String name;
    /**
     * 描述
     */
    @Column(name = "description")
    private String description;
    /**
     * 排序字段
     */
    @Column(name = "sort")
    private Integer sort;
    /**
     * 权限
     */
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "sys_role_permission", joinColumns = {@JoinColumn(name = "role_id")},
    inverseJoinColumns = {@JoinColumn(name = "permission_id")})
    private Set<Permission> permissions;
    /**
     * 用户
     */
    @ManyToMany(mappedBy = "roles")
    private Set<User> users;

    public Role() {
    }

    public Role(String id, String name, String description, Integer sort ) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.sort = sort;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getSort() {
        return sort;
    }

    public void setSort(Integer sort) {
        this.sort = sort;
    }

    public Set<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(Set<Permission> permissions) {
        this.permissions = permissions;
    }

    public Set<User> getUsers() {
        return users;
    }

    public void setUsers(Set<User> users) {
        this.users = users;
    }

    /**
     * 返回权限名称集合
     * @return 权限名称集合
     */
    @Transient //非数据库字段
    public Set<String> getPermissionsName() {
        Set<Permission> permissions = getPermissions();
        Set<String> set = new HashSet<String>();
        for (Permission permission : permissions) {
            set.add(permission.getName());
        }
        return set;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}
